package com.jiazhong.example.project.bookstore.front.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.jiazhong.example.project.bookstore.commons.bean.Book;
import com.jiazhong.example.project.bookstore.commons.config.JwtConfig;
import com.jiazhong.example.project.bookstore.commons.util.JsonResult;
import com.jiazhong.example.project.bookstore.front.service.BookService;
import com.jiazhong.example.project.bookstore.front.service.impl.ShoppingCartServiceImpl;
import com.jiazhong.example.project.bookstore.front.service.impl.UserServiceImpl;
import io.jsonwebtoken.Claims;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
@RestController
@RequestMapping("/book")
public class BookController {
    @Autowired
    private BookService bookService;

    @GetMapping("/fresh/{number}")
    public JsonResult findFresh(@PathVariable("number") int number) {
        return bookService.findFresh(number);
    }

    @GetMapping("/lower/{number}")
    public JsonResult findLower(@PathVariable("number") int number) {
        return bookService.findLower(number);
    }

    @GetMapping("/fresh_all/{page}")
    public JsonResult findFreshAll(@PathVariable("page") int page, HttpServletRequest request) {
        return bookService.findFreshAll(page, request.getHeader("token"));
    }

    @GetMapping("/lower_all/{page}")
    public JsonResult findLowerAll(@PathVariable("page") int page, HttpServletRequest request) {
        return bookService.findLowerAll(page, request.getHeader("token"));
    }

    @GetMapping("/category/{categoryId}/{page}")
    public JsonResult findBookByCategoryId(@PathVariable("page") int page, @PathVariable("categoryId") String categoryId, HttpServletRequest request) {
        JsonResult<IPage<Book>> result = bookService.findBookByCategoryId(page, categoryId, request.getHeader("token"));
        IPage<Book> data = result.getData();
        List<Book> list = data.getRecords();
        List<Book> list1 = checkExistsCart(list, request.getHeader("token"));
        data.setRecords(list1);
        return result;
    }

    @GetMapping("/search/{bookname}/{page}")
    public JsonResult findBookByBookname(@PathVariable("page") int page, @PathVariable("bookname") String bookname, HttpServletRequest request) {
        return bookService.findBookByBookname(page, bookname, request.getHeader("token"));
    }

    @GetMapping("/find_bookname_fresh/{bookname}/{page}")
    public JsonResult findBookByBooknameAndFresh(@PathVariable("bookname") String bookname, @PathVariable("page") int page, HttpServletRequest request) {
        return bookService.findBookByBooknameAndFresh(page, bookname, request.getHeader("token"));
    }

    @GetMapping("/find_bookname_lower/{bookname}/{page}")
    public JsonResult findBookByBooknameAndLower(@PathVariable("bookname") String bookname, @PathVariable("page") int page, HttpServletRequest request) {
        return bookService.findBookByBooknameAndLower(page, bookname, request.getHeader("token"));
    }

    @GetMapping("/find_bookname_category/{bookname}/{category}/{page}")
    public JsonResult findBookByBooknameAndCategory(@PathVariable("bookname") String bookname, @PathVariable("category") String category, @PathVariable("page") int page, HttpServletRequest request) {
        return bookService.findBookByBooknameAndCategoryId(page, bookname, category, request.getHeader("token"));
    }

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private List<Book> checkExistsCart(List<Book> list, String token) {
        boolean b = JwtConfig.checkToken(token);
        if (!b) {
            return list;
        }
        Claims claims = JwtConfig.parseJWT(token);
        Object userId = claims.get("id");
        String redisToken = stringRedisTemplate.opsForValue().get(UserServiceImpl.LOGIN_PREFIX + userId);
        if (!Objects.equals(redisToken, token)) {
            return list;
        }
        // 获取到我的购物车
        Map<Object, Object> carts = stringRedisTemplate.opsForHash().entries(ShoppingCartServiceImpl.SHOPPING_CART_PREFIX + userId);
        for (Book book : list) {
            boolean containsKey = carts.containsKey(book.getId());
            if (containsKey) {
                book.setShow(Boolean.TRUE);
            }
        }
        return list;
    }
}
